// 计算多个多边形的中心点
function getCenterOfPolygons(polygons) {
  let sumLat = 0, sumLng = 0;
  let count = 0;
  for (let p of polygons) {
    for (let point of p.points) {
      sumLat += point.latitude;
      sumLng += point.longitude;
      count++;
    }
  }
  return count > 0
    ? { latitude: sumLat / count, longitude: sumLng / count }
    : { latitude: 39.909097, longitude: 116.397026 };
}

Page({
  data: {
    scale: 15,
    polygons: [],
    markers: [],
    showPolygons: true,
    center: { latitude: 39.909097, longitude: 116.397026 }
  },

  onLoad() {
    // 页面加载时自动生成 5 个区域
    this.generateFiveAreas();
  },

  generateFiveAreas() {
    const baseLat = 39.909;
    const baseLng = 116.397;
    const offset = 0.002;

    const colors = [
      '#3388ffDD', '#2ecc71DD', '#e74c3cDD', '#f39c12DD', '#9b59b6DD'
    ];

    const polygons = [];

    for (let i = 0; i < 5; i++) {
      // 创建一个矩形区域
      const points = [
        { longitude: baseLng + i * offset * 0.8, latitude: baseLat + i * offset },
        { longitude: baseLng + 0.001 + i * offset * 0.8, latitude: baseLat + i * offset },
        { longitude: baseLng + 0.001 + i * offset * 0.8, latitude: baseLat + 0.001 + i * offset },
        { longitude: baseLng + i * offset * 0.8, latitude: baseLat + 0.001 + i * offset },
        { longitude: baseLng + i * offset * 0.8, latitude: baseLat + i * offset } // 闭合
      ];

      polygons.push({
        id: i + 1,
        points,
        color: colors[i],
        strokeWidth: 3,
        fillColor: colors[i].replace('DD', '33')
      });
    }

    const center = getCenterOfPolygons(polygons);

    this.setData({
      polygons,
      center
    });

    // 初始判断是否需要聚合
    this.updateDisplayMode(this.data.scale);
  },

  onRegionChange(e) {
    if (e.type === 'end') {
      const mapCtx = wx.createMapContext('areaMap');
      mapCtx.getScale({
        success: (res) => {
          const scale = Math.round(res.scale);
          this.updateDisplayMode(scale);
        }
      });
    }
  },

  updateDisplayMode(scale) {
    const count = this.data.polygons.length;
    if (scale <= 12 && count > 0) {
      // 缩小：显示聚合数字
      const center = getCenterOfPolygons(this.data.polygons);
      const markers = [{
        id: 9999,
        latitude: center.latitude,
        longitude: center.longitude,
        callout: {
          content: `${count}`,
          color: '#fff',
          fontSize: 16,
          bgColor: '#f00',
          borderRadius: 16,
          padding: 6,
          display: 'ALWAYS'
        }
      }];

      this.setData({
        showPolygons: false,
        markers,
        scale
      });
    } else {
      // 放大：显示多边形
      this.setData({
        showPolygons: true,
        markers: [],
        scale
      });
    }
  }
});